#!/usr/bin/python
import random
import MySQLdb
import cgi, cgitb 
from config import *

form = cgi.FieldStorage()
configure = config()
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62_decode(string, alphabet=ALPHABET):
    """Decode a Base X encoded string into the number

    Arguments:
    - `string`: The encoded string
    - `alphabet`: The alphabet to use for encoding
    """
    base = len(alphabet)
    strlen = len(string)
    num = 0

    idx = 0
    for char in string:
        power = (strlen - (idx + 1))
        num += alphabet.index(char) * (base ** power)
        idx += 1

    return num

def redirect(url):
	#print "Status: 302 Moved"
	#print "Location: %s" % url
	#print
	
    print "Content-Type: text/plain"
    print "Refresh: 0; url=%s" % url
    print
    print "Redirecting..."
	
code = form.getvalue('code')
if(code==None):
    print 'Content-type: text/html\n\n'
    headerPrint()
    print "<h2><font color='red'>Access Denied</font></h2>"
    footerPrint()
    exit()
key = ""
for i in range(len(code)):
    key = key + str(base62_decode(code[i]))
try:
    db = MySQLdb.connect(host=configure.dbHostname,user=configure.dbUsername,passwd=configure.dbPassword,db=configure.dbName)
    sql = """select link from link_database where hash=%s""" %(key)
    db.query(sql)
    result = db.store_result()
except MySQLdb.Error, e:
     print "Error %d: %s" % (e.args[0], e.args[1])
link = result.fetch_row()
url = link[0][0]
#print "Content-Type: text/html\n\n"
#print url
if(len(link)!=0):
    redirect(url)
else:
    print "Content-Type: text/html\n\n"
    print "Url not found"
